#!/user/bin/env node

const log = console.log;
const koabody = require('koa-body'),
      path = require('path'),
      Koa = require('koa'),
      Router = require('koa-router'),
      router = new Router(),
      bodyparser = require('koa-bodyparser'),
      app = new Koa(),
      fs = require('fs');

app.use(koabody({
  multipart:true,
  formidable:{
    maxFileSize:200*1024*1024   //上传文件大小限制
  }
}));

router.get('/',async (ctx,next)=>{
  ctx.body = uploadPage;
  next();
})
router.post('/upload',async (ctx,next)=>{
  const file = ctx.request.files.file;
  //log(file)
  const reader = fs.createReadStream(`${file.path}`);
  let filePath = path.join(__dirname,'./uploadfile' + `/${file.name}`);
  const upStream = fs.createWriteStream(filePath);
  reader.pipe(upStream);
  
  ctx.body = '上传成功';
})

app.use(router.routes()); 
app.listen(3000);

const uploadPage = `
  <!DOCTYPE html>
  <html>
    <head>
      <meta charset="UTF-8">
      <title>Upload File</title>
    </head>
    <body>
      <h1>Upload File</h1>
      <form method="post" enctype="multipart/form-data" action="/upload">
        <input type="file" name="file" id='file' value='' multiple='multiple' />
        <input type="submit" value="提交" />
      </form>
    </body>
  </html>`;

